import rclpy
from status_interfaces.msg import SystemStatus
from rclpy.node import Node
import psutil
import platform

class SysStatusPub(Node):
    def __init__(self, node_name):
        super().__init__(node_name)
        self.status_publisher_ = self.create_publisher(SystemStatus, 'sys_status', 10)  # 创建发布者
        self.timer_ = self.create_timer(1.0, self.timer_callback)    # 设定一个定时器

    def timer_callback(self):   # 回调函数
        cpu_percent = psutil.cpu_percent()  # CPU使用百分比
        memory_info = psutil.virtual_memory()   # 内存信息
        net_io_counters = psutil.net_io_counters()  # 网络相关内容
        
        msg = SystemStatus()
        msg.stamp = self.get_clock().now().to_msg() # 时间戳
        msg.host_name = platform.node() # 计算机的名字
        msg.cpu_percent = cpu_percent   # CPU使用率
        msg.memory_percent = memory_info.percent    # 内存使用率
        msg.memory_total = memory_info.total / 1024 / 1024   # 内存总大小
        msg.memory_available = memory_info.available / 1024 / 1024    # 有效内存
        msg.net_sent = net_io_counters.bytes_sent / 1024 / 1024   # 网络发送的数据总量(MB)
        msg.net_recv = net_io_counters.bytes_recv / 1024 / 1024  # 网络接收的数据总量(MB)
        
        self.get_logger().info(f'发布：{str(msg)}')
        self.status_publisher_.publish(msg)

def main():
    rclpy.init()
    node = SysStatusPub('sys_status_pub')
    rclpy.spin(node)
    rclpy.shutdown()
    